package com.android.pinprovince.view.detail;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.android.pinprovince.R;
import com.android.pinprovince.activity.BaseObject;
import com.android.pinprovince.model.data;
import com.android.pinprovince.model.dataCallback;
import com.android.pinprovince.model.detail.Couponparent;
import com.android.pinprovince.model.detail.MainDetail;
import com.android.pinprovince.model.detail.paydetail;
import com.android.pinprovince.utils.CommonUtils;
import com.android.pinprovince.utils.ConstantsUrl;
import com.android.pinprovince.utils.HttpUtils;
import com.android.pinprovince.utils.LoginState;
import com.android.pinprovince.utils.ObjectUtils;
import com.android.pinprovince.view.MyGridView;
import com.android.pinprovince.view.MyListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/11/16.
 */

public class PopPaycoupn extends PopupWindow implements View.OnClickListener {


    private PopupWindow popupWindow;


    private Context context;
    private paydetail.DataBean PayData;

    private OnPopListDataClickListener poplist_listener;
    private View progress_loading;
    private final View inflate;

    public interface OnPopListDataClickListener {
        void onData(String id, String discount, String need_amount, String title, int posUse, int pos_use);
    }

    public void setPopListDataClickListener(OnPopListDataClickListener listener) {
        this.poplist_listener = listener;
    }


    public PopPaycoupn(Context context, paydetail.DataBean PayData, int pos_use_general) {
        this.pos_use = pos_use_general;
        this.context = context;
        this.PayData = PayData;
        inflate = LayoutInflater.from(context).inflate(R.layout.pop_youhuiquan, null);
        popupWindow = new PopupWindow(inflate, LinearLayoutCompat.LayoutParams.MATCH_PARENT,
                LinearLayoutCompat.LayoutParams.MATCH_PARENT, true);
        popupWindow.setAnimationStyle(R.style.popWindow_anim_style);


        inflate.findViewById(R.id.close).setOnClickListener(this);
        inflate.findViewById(R.id.coupon_close).setOnClickListener(this);
        inflate.findViewById(R.id.pop_del).setOnClickListener(this);

    }

    public void close() {

        if (popupWindow != null && popupWindow.isShowing()) {

            popupWindow.dismiss();


        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.close:
            case R.id.coupon_close:
            case R.id.pop_del:
                close();
                break;
            case R.id.ok_tv:
                zixuan_listener.onDataSure();
                break;
        }
    }
    private OnZixuanDataClickListener zixuan_listener;

    public interface OnZixuanDataClickListener {
        void onZixuanData(String id);

        void onDataSure();
    }

    public void setZixuanDataClickListener(OnZixuanDataClickListener zixuan_listener) {
        this.zixuan_listener = zixuan_listener;
    }

    public void show(View parent, String thumb, final List<MainDetail.DataBean.StepArrayBean> List_Zixuan) {
        if (List_Zixuan == null && List_Zixuan.size() > 0 || thumb == null) {

            return;
        }
        inflate.findViewById(R.id.ll_zixuanteam).setVisibility(View.VISIBLE);
        inflate.findViewById(R.id.ok_tv).setOnClickListener(this);
        ImageView iv_adapter_grid_pic = (ImageView) inflate.findViewById(R.id.iv_adapter_grid_pic);
        final TextView real_price_tv = (TextView) inflate.findViewById(R.id.real_price_tv);
        ObjectUtils.photo(context, thumb, iv_adapter_grid_pic);

        MyGridView lv_property = (MyGridView) inflate.findViewById(R.id.lv_property);
        final ZixuanAdapt zixuanAdapt = new ZixuanAdapt(List_Zixuan);
        lv_property.setAdapter(zixuanAdapt);
        real_price_tv.setText("￥" + List_Zixuan.get(0).getStep_value());

        lv_property.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                zixuanAdapt.select(i);
                real_price_tv.setText("￥" + List_Zixuan.get(i).getStep_value());
                zixuan_listener.onZixuanData(List_Zixuan.get(i).getStep_key() + "-" + List_Zixuan.get(i).getStep_value());
            }
        });
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
    }


    private int pos_zixuan = 0;

    class ZixuanAdapt extends BaseAdapter {

        List<MainDetail.DataBean.StepArrayBean> use_list;


        public ZixuanAdapt(List<MainDetail.DataBean.StepArrayBean> use_list) {
            this.use_list = use_list;

        }

        public void refresh(List<MainDetail.DataBean.StepArrayBean> list) {
            use_list = list;
            notifyDataSetChanged();
        }

        // 选中当前选项时，让其他选项不被选中
        public void select(int position) {
            pos_zixuan = position;
            notifyDataSetChanged();

        }

        @Override
        public int getCount() {
            return use_list.size();
        }


        @Override
        public BaseObject getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            View inflate = LayoutInflater.from(context).inflate(R.layout.item_gird_detail_zixuan, null);

            TextView tv = (TextView) inflate.findViewById(R.id.tv);
            tv.setText(use_list.get(position).getStep_key() + "人/￥" + use_list.get(position).getStep_value());
            if (pos_zixuan == position) {//最后选择的位置
                tv.setTextColor(Color.parseColor("#ffffff"));
                tv.setBackgroundResource(R.drawable.corner_red_bg);
            } else {
                tv.setTextColor(Color.parseColor("#333333"));
                tv.setBackgroundResource(R.drawable.corner_gray_bg);
            }


            return inflate;
        }
    }

    public void show(View parent, int type,Double object) {
        if (PayData == null) {

            return;
        }

        ShowTypeUse(type,object);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
    }


    private String coupon_id_use = "";
    private String coupon_discount_use = "";
    private String coupon_need_amount_use = "";
    private String coupon_title_use = "";
    private List<Couponparent> use_coupon = new ArrayList<>();
    private List<Couponparent> dis_coupon = new ArrayList<>();



    private void AddToUseOrDis(Double totalprice,Double need,Couponparent coupon){
       if(totalprice>=need){
           use_coupon.add(coupon);
       }else {
           dis_coupon.add(coupon);
       }
    }
    /**
     *
     * @param type
     * @param object 用来传入现在的商品总金额；用在判断优惠券是否可以用
     */
    private void ShowTypeUse(final int type,Double object) {
        inflate.findViewById(R.id.ll_coupon).setVisibility(View.VISIBLE);
        TextView coupon_title = (TextView) inflate.findViewById(R.id.coupon_title);
        progress_loading = inflate.findViewById(R.id.progress_loading);
        MyListView use_list = (MyListView) inflate.findViewById(R.id.use_list);
        MyListView dis_list = (MyListView) inflate.findViewById(R.id.dis_list);
        switch (type) {
            case 0:
                coupon_title.setText("通用优惠券");
                use_coupon.clear();
                dis_coupon.clear();
                if (PayData.getUseable() != null) {
                         int size = PayData.getUseable().size();
                    for (int i = 0; i < size; i++) {
                        paydetail.DataBean.UseableBean useable=   PayData.getUseable().get(i);

                        Couponparent Couponparent = new Couponparent();
                        Couponparent.id = useable.getId()+"" ;
                        Couponparent.discount = useable.getAmount()+"" ;
                        Couponparent.need_amount = useable.getNeed_amount()+"" ;
                        Couponparent.title = useable.getTitle()+"" ;
                        Couponparent.time = useable.getExpire_time()+"" ;
                        Couponparent.coupon_id = useable.getCoupon_id()+"" ;
                        Couponparent.amount = useable.getAmount()+"" ;
/*                        Couponparent Couponparent = new Couponparent(PayData.getUseable().get(i).getId() + "", PayData.getUseable().get(i).getAmount(),
                                PayData.getUseable().get(i).getNeed_amount(), PayData.getUseable().get(i).getTitle(), PayData.getUseable().get(i).getExpire_time(), PayData.getUseable().get(i).getCoupon_id());*/

                        Double need = CommonUtils.StringToDouble(PayData.getUseable().get(i).getNeed_amount());
                        AddToUseOrDis(object,need,Couponparent);
                       // use_coupon.add(Couponparent);
                    }
                }
                if (PayData.getDisable() != null) {
                    int size2 = PayData.getDisable().size();
                    for (int i = 0; i < size2; i++) {
//                        Couponparent Couponparent = new Couponparent(PayData.getDisable().get(i).getAmount(), PayData.getDisable().get(i).getTitle(),
//                                PayData.getDisable().get(i).getExpire_time());
                        paydetail.DataBean.DisableBean unuseable=   PayData.getDisable().get(i);
                        Couponparent Couponparent = new Couponparent();
                        Couponparent.id = unuseable.getId()+"" ;
                        Couponparent.discount = unuseable.getAmount()+"" ;
                        Couponparent.need_amount = unuseable.getNeed_amount()+"" ;
                        Couponparent.title = unuseable.getTitle()+"" ;
                        Couponparent.time = unuseable.getExpire_time()+"" ;
                        Couponparent.coupon_id = unuseable.getCoupon_id()+"" ;
                        Couponparent.amount = unuseable.getAmount()+"" ;
                        Double need = CommonUtils.StringToDouble(unuseable.getNeed_amount());
                        AddToUseOrDis(object,need,Couponparent);
                        //dis_coupon.add(Couponparent);
                    }
                }
                break;
            case 1:
                coupon_title.setText("店铺优惠券");
                use_coupon.clear();
                dis_coupon.clear();
                if (PayData.getSeller_useable() != null) {
                       int size3=PayData.getSeller_useable().size();
                    for (int i = 0; i < size3; i++) {
                        paydetail.DataBean.SellerUseableBean unuseable=   PayData.getSeller_useable().get(i);

                        Couponparent Couponparent = new Couponparent();
                        Couponparent.id = unuseable.getId()+"" ;
                        Couponparent.discount = unuseable.getAmount()+"" ;
                        Couponparent.need_amount = unuseable.getNeed_amount()+"" ;
                        Couponparent.title = unuseable.getTitle()+"" ;
                        Couponparent.time = unuseable.getExpire_time()+"" ;
                        Couponparent.coupon_id = unuseable.getCoupon_id()+"" ;
                        Couponparent.amount = unuseable.getAmount()+"" ;
                        Double need = CommonUtils.StringToDouble(unuseable.getNeed_amount());
                        AddToUseOrDis(object,need,Couponparent);
                       /* Couponparent Couponparent = new Couponparent(PayData.getSeller_useable().get(i).getId() + "", PayData.getSeller_useable().get(i).getAmount(),
                                PayData.getSeller_useable().get(i).getNeed_amount(), PayData.getSeller_useable().get(i).getTitle(), PayData.getSeller_useable().get(i).getExpire_time(),
                                PayData.getSeller_useable().get(i).getCoupon_id());
                        use_coupon.add(Couponparent);*/
                    }
                }
                if (PayData.getSeller_unreceive() != null) {
                    int size4=PayData.getSeller_unreceive().size();
                    for (int i = 0; i < size4; i++) {
                        paydetail.DataBean.SellerUnreceiveBean unuseable=   PayData.getSeller_unreceive().get(i);
                        Couponparent Couponparent = new Couponparent();
                        Couponparent.id = unuseable.getId()+"" ;
                        Couponparent.discount = unuseable.getAmount()+"" ;
                        Couponparent.need_amount = unuseable.getNeed_amount()+"" ;
                        Couponparent.title = unuseable.getTitle()+"" ;
                        Couponparent.time = unuseable.getExpire_time()+"" ;
                        Couponparent.coupon_id = unuseable.getCoupon_id()+"" ;
                        Couponparent.amount = unuseable.getAmount()+"" ;
                        Double need = CommonUtils.StringToDouble(unuseable.getNeed_amount());
                        AddToUseOrDis(object,need,Couponparent);


                      /*  Couponparent Couponparent = new Couponparent(PayData.getSeller_unreceive().get(i).getId() + "", PayData.getSeller_unreceive().get(i).getAmount(),
                                PayData.getSeller_unreceive().get(i).getNeed_amount(), PayData.getSeller_unreceive().get(i).getTitle(),
                                (String) PayData.getSeller_unreceive().get(i).getExpire_time(), (String) PayData.getSeller_unreceive().get(i).getCoupon_id());
                        use_coupon.add(Couponparent);*/
                    }
                }

                if (PayData.getSeller_disable() != null) {
                    int size5=PayData.getSeller_disable().size();
                    for (int i = 0; i < size5; i++) {
                        paydetail.DataBean.SellerDisableBean unuseable=   PayData.getSeller_disable().get(i);
                        Couponparent Couponparent = new Couponparent();
                        Couponparent.id = unuseable.getId()+"" ;
                        Couponparent.discount = unuseable.getAmount()+"" ;
                        Couponparent.need_amount = unuseable.getNeed_amount()+"" ;
                        Couponparent.title = unuseable.getTitle()+"" ;
                        Couponparent.time = unuseable.getExpire_time()+"" ;
                        Couponparent.coupon_id = unuseable.getCoupon_id()+"" ;
                        Couponparent.amount = unuseable.getAmount()+"" ;
                        Double need = CommonUtils.StringToDouble(unuseable.getNeed_amount());
                        AddToUseOrDis(object,need,Couponparent);


                     /*   Couponparent Couponparent = new Couponparent(PayData.getSeller_disable().get(i).getAmount(), PayData.getSeller_disable().get(i).getTitle(),
                                PayData.getSeller_disable().get(i).getExpire_time());
                        dis_coupon.add(Couponparent);*/
                    }
                }
                break;
        }


        final useCouponAdapt adapt_use = new useCouponAdapt(use_coupon);
        use_list.setAdapter(adapt_use);
        use_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                adapt_use.select(position);
                if (position == 0) {
                    coupon_id_use = "0";
                    coupon_discount_use = "0";
                    coupon_need_amount_use = "-1";
                    coupon_title_use = "不使用优惠券";
                } else {
                    coupon_need_amount_use = use_coupon.get(position - 1).getNeed_amount();
                    coupon_discount_use = use_coupon.get(position - 1).getDiscount();
                    coupon_title_use = use_coupon.get(position - 1).getTitle();
                    coupon_id_use = use_coupon.get(position - 1).getId();
                }

                poplist_listener.onData(coupon_id_use, coupon_discount_use, coupon_need_amount_use, coupon_title_use, pos_use, type);
            }
        });


        disCouponAdapt adapt_dis = new disCouponAdapt(dis_coupon);
        dis_list.setAdapter(adapt_dis);

    }


    private int pos_use;

    class useCouponAdapt extends BaseAdapter {

        List<Couponparent> use_list;


        public useCouponAdapt(List<Couponparent> use_list) {
            this.use_list = use_list;

        }

        public void refresh(List<Couponparent> list) {
            use_list = list;
            notifyDataSetChanged();
        }

        // 选中当前选项时，让其他选项不被选中
        public void select(int position) {
            pos_use = position;
            notifyDataSetChanged();

        }

        @Override
        public int getCount() {
            return use_list.size() + 1;
        }


        @Override
        public BaseObject getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }


        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            View inflate = LayoutInflater.from(context).inflate(R.layout.item_pay_coupon, null);
            View nouse_ll = inflate.findViewById(R.id.nouse_ll);
            View use_ll = inflate.findViewById(R.id.use_ll);

            TextView price = (TextView) inflate.findViewById(R.id.price);
            TextView price1 = (TextView) inflate.findViewById(R.id.price1);
            TextView price2 = (TextView) inflate.findViewById(R.id.price2);
            final RadioButton address_check = (RadioButton) inflate.findViewById(R.id.item_list_mine_address_check);

            final TextView coupon_get = (TextView) inflate.findViewById(R.id.item_list_mine_address_get);
            if (pos_use == position) {//最后选择的位置
                address_check.setChecked(true);
            } else {
                address_check.setChecked(false);
            }

            if (position == 0) {
                use_ll.setVisibility(View.GONE);
                nouse_ll.setVisibility(View.VISIBLE);
            } else {
                price.setText(use_list.get(position - 1).getDiscount());
                price1.setText(use_list.get(position - 1).getTitle());

                if (use_list.get(position - 1).getTime().equals("0") || use_list.get(position - 1).getTime() == null) {
                    price2.setText("有效期不限");
                } else {

                    String strTime = ObjectUtils.getStrTime(use_list.get(position - 1).getTime(), "yyyy-MM-dd");
                    price2.setText("有效期至" + strTime);

                }
                if (use_list.get(position - 1).getCoupon_id() == null) {

                    coupon_get.setVisibility(View.VISIBLE);
                    address_check.setVisibility(View.GONE);
                    coupon_get.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            getcoupon(use_list.get(position - 1).getId(), address_check, coupon_get);

                        }
                    });

                } else {

                    address_check.setVisibility(View.VISIBLE);
                    coupon_get.setVisibility(View.GONE);

                }

            }


            return inflate;
        }
    }

    class disCouponAdapt extends BaseAdapter {

        List<Couponparent> dis_list;

        public disCouponAdapt(List<Couponparent> nouseyouhuiquan) {

            this.dis_list = nouseyouhuiquan;
        }

        public void refresh(List<Couponparent> list) {
            dis_list = list;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return dis_list.size();
        }


        @Override
        public BaseObject getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position) {
            return 0;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View inflate = LayoutInflater.from(context).inflate(R.layout.item_noyouhuiquan, null);
            TextView price = (TextView) inflate.findViewById(R.id.price);
            TextView price1 = (TextView) inflate.findViewById(R.id.price1);
            TextView price2 = (TextView) inflate.findViewById(R.id.price2);
            Couponparent disableBean = dis_list.get(position);
            price.setText(disableBean.getAmount());
            price1.setText(disableBean.getTitle());
            if (disableBean.getTime() == null || disableBean.getTime().equals("0")) {

                price2.setText("有效期不限");

            } else {
                String strTime = ObjectUtils.getStrTime(disableBean.getTime(), "yyyy-MM-dd");
                price2.setText("有效期至" + strTime);

            }
            return inflate;
        }
    }

    private void getcoupon(String id, final RadioButton address_check, final TextView coupon_get) {

        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERCOLLECTSTOREGETYOUHUIQUAN + "?id=" + id;
        boolean networkConnected = ObjectUtils.isNetworkConnected(context);
        if (networkConnected) {
            progress_loading.setVisibility(View.VISIBLE);
            String getid = LoginState.getInstance().getid(context);
            String getpd = LoginState.getInstance().getpd(context);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new dataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    progress_loading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(data response, int id) {
                    progress_loading.setVisibility(View.GONE);

                    if (response.getCode() == 0) {

                        address_check.setVisibility(View.VISIBLE);
                        coupon_get.setVisibility(View.GONE);
                    }
                    ObjectUtils.toast(context, response.getMsg());
                }
            });
        } else {

            ObjectUtils.toast(context, "网络未连接");
        }

    }
}
